<!--
 /**
 * Author: hongChengHao
 * Date: 2022-07-21 14:23
 * Desc: 电影券
 */
-->
<template>
  <view class="film-coupon">
    <!-- #ifdef MP-WEIXIN || MP-ALIPAY-->
    <yy-navbar :auto-back="false" @left-click="backClick" title="电影券" bg-color="#fff"></yy-navbar>
    <!-- #endif-->
    <view class="film-coupon__search">
      <view class="film-coupon__input">
        <u-input class="film-coupon__uipt" placeholder="输入电影券密码绑定" v-model="cardCode" type="text" clearable />
        <view class="film-coupon__scan" @click.stop="onScan"></view>
      </view>
      <view class="film-coupon__bind-btn" @click="bindCoupon">绑定</view>
    </view>
    <view class="film-coupon__tabs">
      <u-tabs
        v-model="activeTab"
        :list="arr"
        :scrollable="false"
        @change="change"
        label-key="name"
        val-key="couponType"
        :active-style="{
          color: '#3BC5D2',
          fontWeight: 'bold',
          transform: 'scale(1.05)'
        }"
        line-color="#3BC5D2"
      ></u-tabs>
    </view>
    <view :class="listDataLength ? 'film-coupon__content' : ''">
      <yy-list :list="listData" :loading="listLoading" :finished="fromPage ? true : listFinished" empty-type="coupon">
        <coupon-box class="film-coupon__coupon-box" v-for="(item, index) in listData" :can-use="getCanUse(item)" :key="item.couponId">
          <view slot="left" class="film-coupon__coupon-main" :class="{ 'film-coupon__coupon-main--extr': activeTab === '2' }" @click="toDetail(item.couponId)">
            <view v-if="activeTab === '2'" class="mr10">
              <view style="line-height: 1.5">
                <text style="color: #3bc5d2; font-size: 30rpx">￥</text>
                <text class="mr10" style="color: #3bc5d2; font-size: 45rpx">{{ item.showReduce }}</text>
              </view>
              <view class="tc" style="color: #3bc5d2">满{{ item.fullAmount }}元可用</view>
            </view>
            <view style="box-sizing: border-box">
              <view v-if="activeTab === '1'" class="film-coupon__coupon-money">{{ item.couponName || '--' }}</view>
              <view v-else class="pt10 mb10">满{{ item.fullAmount }}元减{{ item.showReduce }}元立减券</view>
              <view class="mb10">有效期： {{ item.sD || '--' }}~{{ item.eD || '--' }}</view>
              <view v-if="activeTab === '1'" class="onShow w500 mb10">{{ item.useTip[0] }}</view>
              <view @click.stop="noDo" v-if="(item.couponCount == 1 && item.usable) || item.showCoupon">
                <view @click.stop="onSel(itemP, index, indexP)" v-for="(itemP, indexP) in getCouponList(item)" :key="indexP">
                  <view class="password mb10">
                    <view v-if="!fromPage" class="w20 h20 flex-c-m">
                      <view class="dian"></view>
                    </view>
                    <view v-if="item.usable && fromPage" class="check" :class="itemP.isSel === '1' ? 'checked' : 'no-check'"></view>
                    <view class="ml20">券密码： {{ itemP.couponId || '--' }}</view>
                  </view>
                  <view class="mb10 ml40">券来源： {{ itemP.buyType || '--' }}</view>
                </view>
              </view>
            </view>
          </view>

          <view slot="right">
            <view v-if="fromPage !== 'sureOrder'">
              <view class="flex-col flex-c-m h100p" v-if="item.isFrozen !== '1'">
                <text
                  ><text class="fc-yellow b">{{ item.couponCount }}</text
                  ><text class="fc3">张</text>
                </text>
                <view class="film-coupon__coupon-btn mt10" @click="onUse">立即使用</view>
                <view v-if="item.couponCount != 1" @click="showCoupon(item)" class="fc3 fs20 ptb10">{{ item.showCoupon ? '折叠券密码' : '查看券密码' }}</view>
              </view>
              <view v-else class="film-coupon__coupon-status--freeze"></view>
            </view>

            <view v-else class="film-coupon__select flex-col flex-c-m h100p">
              <view class="film-coupon__use-bg mb10" :class="item.usable ? 'film-coupon__use' : 'film-coupon__no-use'"></view>
              <text
                ><text class="fc-yellow b">{{ item.couponCount }}</text
                ><text class="fc3">张</text>
              </text>
              <view v-if="item.couponCount != 1 && item.usable" @click="showCoupon(item)" class="fc3 fs20 ptb10">{{ item.showCoupon ? '折叠券密码' : '查看券密码' }}</view>
            </view>
          </view>
        </coupon-box>
      </yy-list>
    </view>
    <check-film-coupon
      title="历史记录"
      :type="checkFilmCouponType"
      :arr="selBox"
      :limit-num="limitNum"
      :active-tab="activeTab"
      :film-price="filmPrice"
      :single-seat-price="singleSeatPrice"
      url="/pagesOrder/filmInvalidCoupon/index"
      @select="select"
    ></check-film-coupon>
  </view>
</template>
<script>
  import CouponBox from '@/pagesOrder/components/CouponBox/index.vue'
  import CheckFilmCoupon from '@/pagesOrder/components/CheckFilmCoupon'
  import listMixins from '@/mixins/listMixins'
  import { deDupArray } from '@/utils'
  import { locSelCoupon } from '@/utils/locStore/data'
  // #ifdef H5
  import { scanQRCode } from '@/utils/sdk'
  import { toast } from '@/utils/message'
  import { locActivityPrize } from '@/utils/locStore/data'
  // #endif
  export default {
    name: 'film-coupon',
    components: { CouponBox, CheckFilmCoupon },
    mixins: [listMixins],
    data() {
      return {
        cardCode: '',
        arr: [
          { name: '兑换券', couponType: '1' },
          { name: '优惠券', couponType: '2' }
        ],
        activeTab: '1',
        fromPage: '',
        flag: false,
        selBox: [],
        maxNum: 1,
        filmPrice: '',
        orderId: '',
        fromPath: '',
        singleSeatPrice: '',
        isAutoBind: false
        // query: {}
      }
    },
    // #ifdef MP-ALIPAY
    onUnload() {
      console.log('this.clickUse', this.clickUse)
      if (!this.clickUse) {
        if (this.fromPath === 'pagesOrder/sureOrder/index') {
          uni.setStorageSync('filmCouponBack', '1')
          const pages = getCurrentPages()
          const page = pages[pages.length - 1]
          console.log('++++handleUnlockSeat+++++setIsReload', pages)
          console.log('++++handleUnlockSeat+++++setIsReload', page)
          if (page) {
            page.onShow()
          }
          // this.$tools.navigateTo(-1)
        }
      }
    },
    // #endif
    onLoad(option) {
      // #ifdef MP-WEIXIN
      if (option.autoBind) {
        this.autoBindCoupon(option.couponId)
      }
      // #endif
      this.fromPath = this.$tools.getCurrentPage().fromPath
      console.log(this.fromPath, 'this.fromPath')
      console.log(option, '  console.log(option)')
      this.fromPage = option.fromPage || ''
      if (this.fromPage) {
        this.canLoading = false
        this.orderId = option.orderId
        this.maxNum = option.maxNum
        this.filmPrice = option.filmPrice
        this.singleSeatPrice = option.singleSeatPrice
      }
      console.log(locSelCoupon.get(), 'asdsda')
      this.selBox = locSelCoupon.get() instanceof Array ? locSelCoupon.get() : []
      console.log(this.selBox, 'this.selBox')
    },
    onShow() {
      this.listLoad()
    },
    // // #ifdef H5
    // beforeRouteLeave(to, from, next) {
    //   if (this.isAutoBind) {
    //     console.log('自动绑定物理返回')
    //     this.$tools.navigateTo('/pages/index/index', {}, 'reLaunch')
    //   } else {
    //     next()
    //   }
    // },
    // // #endif
    // onBackPress(options) {
    //   console.log(options, 'asd')
    //   if (options.from === 'backbutton') {
    //     this.$tools.navigateTo('pages/mine/index', {}, 'switchTab')
    //   }
    //   return true
    // },
    methods: {
      onloadList() {
        console.log(this.orderId, 'this.orderId')
        const couponId = this.selBox
          .map((i) => i.couponId)
          .filter((i) => i)
          .join(',')
        const upId = this.selBox
          .map((i) => i.upId)
          .filter((i) => i)
          .join(',')
        const query = {
          ...this.pageInfo,
          ...{
            couponType: this.activeTab,
            invalid: '1',
            orderId: this.orderId,
            couponId,
            listType: '2'
          }
        }

        const getCouponApi = this.fromPage ? uni.$api.coupon.getCouponByOrderFilm : uni.$api.coupon.getCouponList

        return getCouponApi(query).then((res) => {
          if (this.isLoading) {
            // 是下啦刷新 清空
            this.listData = []
          }

          let listData = []
          if (this.fromPage) {
            listData = res
              .map((item) => {
                if (item.couponType === this.activeTab) {
                  if (item.usable && upId.includes(item.cId)) {
                    item.showCoupon = true
                  }
                  return item
                }
              })
              .filter(Boolean)
          } else {
            listData = [...this.listData, ...res.list]
          }

          this.listData = deDupArray(listData, 'couponId')
          this.$nextTick(() => {
            this.onReplace()
          })
          return res
        })
      },

      getCouponList(item) {
        if (item.couponList && item.couponList.length > 0) {
          return item.couponList
        }
        return [
          {
            couponId: item.couponId,
            buyType: item.buyType
          }
        ]
      },
      change(val) {
        this.activeTab = val.couponType
        this.listRefresh()
        console.log(this.fromPage, 'this.fromPage')
        if (this.fromPage) {
          this.$nextTick(() => {
            console.log(this.selBox, 'this.selBox')
            this.onReplace()
          })
        }
      },
      showCoupon(item) {
        if (item.showCoupon) {
          this.$set(item, 'showCoupon', false)
          // item.showCoupon = false
        } else {
          this.$set(item, 'showCoupon', true)
          // item.showCoupon = true
          if (!item.couponList || item.couponList.length === 0) {
            uni.$api.coupon.getCouponDetailList({ cId: item.cId }).then((res) => {
              this.$set(item, 'couponList', res)
            })
          }
        }
      },
      onPullDownRefresh() {
        this.listRefresh()
      },
      onReachBottom() {
        if (this.canLoading) {
          this.listLoad()
        }
      },
      onScan() {
        // #ifdef MP-ALIPAY
        uni.scanCode({
          success: (res) => {
            this.bindCode(res.result)
          }
        })
        // #endif
        // #ifdef MP-WEIXIN || MP-TOUTIAO
        uni.authorize({
          scope: 'scope.camera',
          success: () => {
            uni.scanCode({
              success: (res) => {
                this.bindCode(res.result)
              }
            })
          },
          fail: () => {
            //授权失败
            uni.showModal({
              title: '该功能需摄像头授权',
              content: '是否进入权限管理，调整授权？',
              success: (res) => {
                if (res.confirm) {
                  //调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
                  uni.openSetting({
                    success: (res) => {
                      console.log(res.authSetting)
                    }
                  })
                } else if (res.cancel) {
                  return uni.showToast({
                    title: '已取消！'
                  })
                }
              }
            })
          }
        })

        // #endif
        // #ifdef H5
        scanQRCode().then((res) => {
          this.bindCode(res)
        })
        // #endif
      },
      bindCode(res) {
        uni.$api.card.qrCodeBind({ qrCode: res }).then(() => {
          this.$msg.toast('绑定成功', 'success')
          setTimeout(() => {
            this.listRefresh()
          }, 1500)
        })
      },
      bindCoupon() {
        if (this.cardCode) {
          uni.$api.coupon.bindCoupon({ couponId: this.cardCode }).then(() => {
            this.$msg.toast('绑定成功', 'success')
            setTimeout(() => {
              this.listRefresh()
            }, 1500)
          })
        } else {
          this.$msg.toast('请输入券密码')
        }
      },
      autoBindCoupon(carCode) {
        this.isAutoBind = true
        uni.$api.coupon.bindCoupon({ couponId: carCode }).then(() => {
          this.$msg.toast('绑定成功', 'success')
          setTimeout(() => {
            this.listRefresh()
          }, 1500)
        })
      },
      getCanUse(item) {
        if (this.fromPage !== 'sureOrder') {
          return true
        }
        let isSame = true
        this.selBox.forEach((val) => {
          if (item.douyinOrderNo !== val.douyinOrderNo) {
            isSame = false
          }
        })
        if (isSame) {
          return true
        } else {
          return false
        }
      },
      onSel(item, index, indexP) {
        console.log('onSel', this.fromPage, this.selBox, item)
        if (!this.fromPage) {
          return
        }
        if (item.usable) {
          if (this.selBox && this.selBox.length > 0 && this.activeTab !== this.selBox[0].type) {
            this.selBox = []
          }
          if (this.activeTab === '1') {
            if (item.isSel === '1') {
              item.isSel = '0'
              this.$set(this.listData[index].couponList, indexP, item)
              this.$nextTick(() => {
                this.selBox = this.selBox.filter((val) => val.couponId !== item.couponId)
              })
            } else {
              console.log('this.activeTab ', this.selBox.length, this.limitNum)
              if (this.selBox.length < +this.limitNum) {
                item.isSel = '1'
                item.type = this.activeTab
                this.$set(this.listData[index].couponList, indexP, item)
                this.$nextTick(() => {
                  this.selBox.push(item)
                })
              }
            }
            console.log('this.activeTab ', this.listData)
          } else {
            if (item.isSel !== '1') {
              this.listData.forEach((val, idx) => {
                if (val.couponId !== item.couponId) {
                  this.$set(item, 'isSel', '0')
                } else {
                  this.$set(item, 'isSel', '1')
                  this.$set(item, 'type', this.activeTab)
                  this.$nextTick(() => {
                    this.selBox.splice(0, 1, val)
                  })
                }
              })
            } else {
              this.$set(item, 'isSel', '0')
              this.$nextTick(() => {
                this.selBox.splice(0, 1)
              })
            }
          }
        }
      },
      onUse() {
        this.clickUse = true
        this.$tools.navigateTo('/pages/ticket/ticket', {}, 'switchTab')
      },
      toDetail(id) {
        const query = { couponId: id, isFromSureOrder: this.fromPage }
        this.$tools.navigateTo('/subPages/rightsCodeDetail/index', query)
      },
      noDo() {
        //v-for不能click.stop 外层盖住
      },
      onReplace() {
        if (this.selBox && this.selBox.length > 0 && this.activeTab === this.selBox[0].type) {
          const ids = this.selBox.map((item) => item.couponId)
          this.listData.forEach((item, index) => {
            item.couponList.forEach((i, idx) => {
              if (ids.includes(i.couponId)) {
                this.$set(i, 'isSel', '1')
              }
            })
          })
        }
      },
      backClick() {
        if (this.fromPath === 'pagesOrder/sureOrder/index') {
          uni.setStorageSync('filmCouponBack', '1')
          this.$tools.navigateTo(-1)
        } else if (this.fromPath === 'pagesOrder/order/detail') {
          this.$tools.navigateTo(-1)
        } else if (this.isAutoBind) {
          //自动绑定
          this.$tools.navigateTo('/pages/index/index', {}, 'switchTab')
        } else {
          this.$tools.navigateTo('/pages/mine/index', {}, 'switchTab')
        }
      },
      select(arr) {
        this.clickUse = true
        console.log('arr', arr)
        uni.setStorageSync('fromCouponList', '1') //储存跳转过券列表
        locSelCoupon.set(arr)
        this.$tools.navigateTo(-1)
      }
    },

    computed: {
      listDataLength() {
        return this.listData.length > 0
      },
      limitNum() {
        return this.activeTab === '1' ? +this.maxNum : 1
      },
      checkFilmCouponType() {
        return this.fromPage !== 'sureOrder' ? '1' : '2'
      }
    }
  }
</script>
<style lang="scss" scoped>
  .film-coupon {
    overflow-x: hidden;
    overflow-y: auto;
    width: 100%;
    min-height: 100vh;
    background: #f3f5f7;
    padding-bottom: 180rpx;
    .tip {
      background-color: #fdf7d7;
      color: #f8a82d;
      font-size: 24rpx;
      text-align: center;
      line-height: 60rpx;
      box-sizing: border-box;
      border-radius: 16rpx;
      height: 60rpx;
    }
    // 搜索
    &__search {
      background: #fff;
      padding: 19rpx 20rpx 23rpx 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1rpx solid #f3f5f7;
      border-bottom: 1rpx solid #f3f5f7;
    }
    &__input {
      margin-right: 10rpx;
      display: flex;
      width: 560rpx;
      height: 72rpx;
      padding-right: 22rpx;
      padding-left: 30rpx;
      background: #f3f5f7;
      border-radius: 20rpx;
    }
    &__uipt {
      margin-right: 10rpx;
      flex: 1;
    }
    &__scan {
      margin-top: 16rpx;
      width: 40rpx;
      height: 40rpx;
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/icon-scan.png) no-repeat;
      background-size: 100%;
    }
    &__bind-btn {
      width: 130rpx;
      height: 68rpx;
      background: linear-gradient(135deg, #55baff 0%, #34f6af 100%);
      border-radius: 20rpx;
      font-size: 28rpx;
      color: #ffffff;
      line-height: 68rpx;
      text-align: center;
    }
    // 标签
    &__tabs {
      // #ifdef MP-ALIPAY
      display: flex;
      justify-content: center;
      align-items: center;
      // #endif
      width: 100vw;
      height: 80rpx;
      background: #ffffff;
    }
    // 内容
    &__content {
      padding: 20rpx;
    }
    &__coupon-main {
      box-sizing: border-box;
      margin-left: 29rpx;
      font-size: 24rpx;
      color: #919191;
      padding: 27rpx 0;
    }
    &__coupon-main--extr {
      margin-top: 20rpx;
      line-height: 2;
      box-sizing: border-box;
      margin-left: unset;
      font-size: 20rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    &__coupon-money {
      margin: 0 0 14rpx 0;
      font-size: 34rpx;
      font-weight: 600;
      color: #333333;
    }
    &__coupon-btn {
      width: 130rpx;
      height: 56rpx;
      background: linear-gradient(135deg, #ffa633 0%, #f8a82d 100%);
      border-radius: 16rpx;
      font-size: 24rpx;
      color: #ffffff;
      line-height: 56rpx;
      text-align: center;
    }
    &__select {
      overflow: hidden;
    }
    &__use-bg {
      width: 66rpx;
      height: 66rpx;
    }
    &__use {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/use-active.png) no-repeat;
      background-size: 100%;
    }
    &__no-use {
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/use-noActive.png) no-repeat;
      background-size: 100%;
    }

    &__coupon-status--freeze {
      margin-top: 48%;
      margin-left: 48%;
      transform: translate(-50%, -50%);
      width: 66rpx;
      height: 66rpx;
      background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/coupon-freeze.png) no-repeat;
      background-size: 100%;
    }
  }
  .password {
    display: flex;
    align-items: center;
  }
  .dian {
    border-radius: 4rpx;
    width: 8rpx;
    height: 8rpx;
    background-color: #3cc5d2;
  }
  .check {
    width: 20rpx;
    height: 20rpx;
  }
  .checked {
    background: url(https://public-oss-file.zmaxfilm.com/applet/img/my/coupon-checked.png) no-repeat;
    background-size: 100%;
  }
  .no-check {
    width: 20rpx;
    height: 20rpx;
    box-sizing: border-box;
    border: 2rpx solid #b2b2b2;
    border-radius: 3rpx;
  }
</style>
